<template>
  <div>
    <!-- 添加商品 -->
    <div>
      <p>
        <span>商品名称</span><input type="text" v-model="$store.state.name" />
      </p>
      <p>
        <span>商品价格</span><input type="text" v-model="$store.state.price" />
      </p>
      <p>
        <span>商品数量</span><input type="text" v-model="$store.state.num" />
      </p>
      <button @click="addFn">添加商品</button>
    </div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th><input type="checkbox" v-model="isAll" /> <span>全选</span></th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(obj, index) in goodList" :key="index">
          <td>
            <input
              type="checkbox"
              :checked="obj.checked"
              @change="
                (e) => {
                  cdChangeStatus(e, index);
                }
              "
            />
          </td>
          <td>{{ obj.name }}</td>
          <td>{{ obj.price }}</td>
          <td>{{ obj.num }}</td>
          <td>{{ obj.num * obj.price }}</td>
          <td><button @click="delFn(index)">删除</button></td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td>合计:{{ intotal }}</td>
          <td colspan="5"></td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {
      data() {
        return {};
      },
    };
  },
  computed: {
    ...mapState(["goodList"]),

    isAll: {
      set(val) {
        // console.log(val);

        this.isAllBig(val);
      },
      get() {
        return this.goodList.every((item) => item.checked === true);
      },
    },
    intotal() {
      return this.goodList.reduce((sum, item) => {
        if (item.checked === true) {
          sum += item.num * item.price;
        }
        return sum;
      }, 0);
    },
  },
  methods: {
    ...mapMutations(["isAllBig", "allPrice"]),
    cdChangeStatus(e, i) {
      // console.log(e.target.checked, i);
      const params = {
        index: i,
        checked: e.target.checked,
      };
      this.$store.commit("statusFn", params);
    },
    delFn(i) {
      this.$store.commit("delOption", i);
    },
    addFn() {
      this.$store.commit("addOption");
    },
  },
};
</script>

<style>
</style>